<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Cache for invidual block
 *
 * Lets you create cache html for block only.
 *
 * @package		Blockcache
 * @author		canhnguyenmanh@vccorp.vn
 */

class Blockcache  extends CI_Controller{
    /*
     * type of cache data: file, memcached or apc
    */
    var $driver='apc';
    
    /*
     * expire time, default: never till delete or system restart
    */
    var $ttl = 3000;
    
    /*
     * extend CI 
    */
	var $_CI;
	
	var $lastData = '';
	var $cDriver = '';
	var $debug = 0;

    function Blockcache () {
		$this->_CI = & get_instance();		
		//$this->_CI->load->library($this->driver);
		if($this->driver){
		    include APPPATH.'libraries/drivers/'.ucfirst($this->driver).'.php';  
		    switch ($this->driver){
                case 'memcached':
                    $this->cDriver = new Memcached();
                    break;
                case 'apc':
                    $this->cDriver = new Apc();
                    break;
            }  
		}
    }

    /*
     * Flexible data APC cache
     * 
     * @ @author canhnm
     */
    function cache ($blockName, $data=null, $ttl=0){
        $lastData = $this->_CI->load->view($blockName, $data, TRUE);
        $blockName = md5($blockName); //hash the blockname to store in cache
		if( !$this->cDriver->is_supported() ){
		    return $lastData;
		}else{
		    if( $this->cDriver->isExists($blockName) ){
		            return $this->cDriver->get( $blockName );   
		    }else{ //if data is not existed then save to cache and return data from view block
		        $this->cDriver->save( $blockName, $lastData, $this->ttl );
		        return $lastData;
		    }
		}
    }
    

    function delete($blockname){
        return $this->cDriver->delete( md5($blockname) );
    }
    
    function deleteAll(){
        return $this->cDriver->clean();
    }
    
}

?>
